package com.yankaizhang.blog.security;

import com.yankaizhang.blog.entity.Log;
import com.yankaizhang.blog.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录失败处理器
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    LogService logService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
        Log log = new Log();
        log.setCreated(System.currentTimeMillis()/1000L);
        log.setContent("尝试登陆失败");
        logService.save(log);
        resp.sendRedirect("/index");
    }
}
